package com.axialproject.health.exchange;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Util {

    public static String loadUrl (String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            StringBuffer buf = new StringBuffer ();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                buf.append(line);
            }
            reader.close();
            return buf.toString();

        } else {
            throw new Exception ("The HTTP response code for GET " + urlString + " is not 200: " + connection.getResponseCode());
        }
    }

    public static String loadUrl (String urlString, String postBody) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(postBody);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            StringBuffer buf = new StringBuffer ();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                buf.append(line);
            }
            reader.close();
            return buf.toString();

        } else {
            throw new Exception ("The HTTP response code for POST " + urlString + " is not 200: " + connection.getResponseCode());
        }
    }

}
